#!/usr/bin/python
import optparse
from socket import *
from threading import *
screenLock=Semaphore(value=1)#用于锁定屏幕，防止占用


#扫描主机+端口
def connScan(tgtHost,tgtPort):
    try:
        connSkt=socket(AF_INET,SOCK_STREAM)
        connSkt.connect((tgtHost,tgtPort))
        screenLock.acquire()
        print('[+]%d/tcp open' % tgtPort)
        try:
            connSkt.send(('ViolentPython').encode('utf8'))
            results = connSkt.recv(45)
            print('[+] ' + str(results))
        except:
            pass
        finally:
            screenLock.release()
            connSkt.close()
    except:
        pass
def portScan(tgtHost,tgtPorts):
    try:
        tgtIp=gethostbyname(tgtHost)
    except:
        print("[-] Connot reslve '%s':Unknown host "%tgtHost)
        return
    try:
        tgtName=gethostbyaddr(tgtIp)
        print("\n[+] Scan Results for:"+tgtIp)
    except:
        print('\n[+] Scan Results for:'+tgtIp)
    setdefaulttimeout(5)
    for tgtPort in tgtPorts:
        try:
            t=Thread(target=connScan,args=(tgtHost,int(tgtPort)))
            t.start()
        except:
            pass
        # print('scanning port '+tgtPort)
        # connScan(tgtHost,int(tgtPort))
def main():
    # 命令行参数解析
    parser = optparse.OptionParser('usage %prog' + '-H <target host> -p <target port>')
    parser.add_option('-H', dest='tgtHost', type='string', help='specify target host')
    parser.add_option('-p', dest='tgtPort', type='string', help='specify target port')
    (options, args) = parser.parse_args()
    tgtHost = options.tgtHost
    tgtPorts = str(options.tgtPort).split(',')#单个输入
    duanPost=str(options.tgtPort).split('-')#段输入
    if tgtHost==None or tgtPorts[0]==None:
        print('[-] You must specify a target host and port[s].')
        exit(0)
    try:
        if duanPost[1]!=None:
            tgtPorts=[]
            for i in range(int(duanPost[0]),int(duanPost[1])):
                tgtPorts.append(str(i+1))
    except:
        pass
    portScan(tgtHost,tgtPorts)
if __name__ == '__main__':
    main()








